import { View, PickerView, PickerViewColumn, Text } from '@tarojs/components';
import theme from '@/theme';
import { ComponentProps, useEffect, useMemo, useState } from 'react';
import './index.scss';
import classNames from 'classnames';
import { Calendar, Icon, PullView, Button } from 'pd-taro-ui';
import { useReactive } from 'ahooks';
import { pxTransform } from '@tarojs/taro';
import { transSelectedValueToValue, transValueToSelectedValue } from '../Select/utils';
import { isEqual } from 'lodash';
import TimePicker from '../TimePicker';
import dayjs from 'dayjs';

interface DateInputProps {
  placeholder?: string;
  value?: string | string[];
  onChange?: (value: DateInputProps['value']) => any;
  onBlur?: any;
  staticed?: boolean;
  disabled?: boolean;
  compProps?: any;
  className?: string;
  /** day单选， range日期范围(start,end) ,  默认day */
  mode?: ComponentProps<typeof Calendar>['mode'];
  /** 是否显示清除按钮 */
  clearable?: boolean;
  /** 是否拼接字符串，返回数组或字符串，默认true字符串 */
  joinValues?: boolean;
  /** 字符串拼接符号，默认, */
  delimiter?: string;
  /** 是否选择时间，默认false */
  showTime?: boolean;
  minDate?: ComponentProps<typeof Calendar>['minDate'];
  maxDate?: ComponentProps<typeof Calendar>['maxDate'];
  disabledDate?: ComponentProps<typeof Calendar>['disabledDate'];
}
const DateInput = ({
  onChange,
  value,
  disabled,
  staticed,
  onBlur,
  clearable = false,
  placeholder = '请选择',
  className,
  compProps,
  mode = 'day',
  joinValues = true,
  delimiter = ',',
  showTime = false,
  minDate,
  maxDate,
  disabledDate,
}: DateInputProps) => {
  const state = useReactive({
    show: false,
    selectedValue: [] as string[],
    searchStr: '',
    times: ['00:00:00', '23:59:59'],
  });
  const hadSelectedValue = !!state.selectedValue.length;

  const open = () => {
    if (disabled) return;
    state.show = true;
  };
  const close = () => {
    state.show = false;
  };
  const submit = () => {
    onChange?.(transSelectedValueToValue(state.selectedValue, mode === 'range', joinValues, delimiter));
    close();
  };
  const clear = () => {
    state.selectedValue = [];
    submit();
  };

  const onChangeCalendar: ComponentProps<typeof Calendar>['onChange'] = val => {
    if (val?.length) {
      let startTime = '';
      let endTime = '';
      if (showTime) {
        startTime = ' ' + dayjs(state.selectedValue[0] || undefined).format('HH:mm:ss') || '00:00:00';
        endTime = ' ' + dayjs(state.selectedValue[1] || undefined).format('HH:mm:ss') || '23:59:59';
      }
      if (mode === 'day') {
        state.selectedValue = [dayjs(val as string).format('YYYY-MM-DD') + startTime];
      } else if (mode === 'range') {
        state.selectedValue = [
          dayjs(val[0] as string).format('YYYY-MM-DD') + startTime,
          dayjs(val[1] as string).format('YYYY-MM-DD') + endTime,
        ];
      }
    }
  };

  const staticStr = useMemo(() => {
    let str = '';
    if (!value?.length) return str;
    if (mode === 'day') {
      str = value as string;
    } else if (mode === 'range') {
      if (joinValues) {
        str = value as string;
      } else {
        str = (value as string[]).join(delimiter);
      }
    }

    return str;
  }, [mode, value, joinValues, delimiter]);

  useEffect(() => {
    if (!state.show) {
      const multiple = mode == 'range';
      const selectedValue = transValueToSelectedValue(value, multiple, joinValues, delimiter);
      if (!isEqual(selectedValue, state.selectedValue.concat())) {
        state.selectedValue = selectedValue;
      }
    }
  }, [delimiter, joinValues, mode, state, state.show, value]);

  if (staticed) {
    return <View className='pd-dateInput--static'>{staticStr}</View>;
  }
  return (
    <>
      <View className={classNames({ 'pd-dateInput': true, 'pd-dateInput--disabled': disabled })}>
        <View className={classNames({ 'pd-dateInput__content': true, 'pd-dateInput__placeholder': !hadSelectedValue })} onClick={open}>
          {staticStr || placeholder || ' '}
        </View>
        {clearable && !disabled && hadSelectedValue && <Icon name='error' color='#bbb' size={36} onClick={clear} />}
        <Icon name='right' color='#bbb' size={36} />
      </View>

      <PullView open={state.show} onClose={close} side='bottom'>
        <View className='pd-dateInput__modal'>
          <View className='pd-dateInput__modal__header'>请选择</View>
          <View className='pd-dateInput__modal__close' onClick={close}>
            <Icon name='close' size={46} />
          </View>
          <Calendar
            mode={mode}
            value={mode === 'day' ? state.selectedValue[0] : state.selectedValue}
            onChange={onChangeCalendar}
            minDate={minDate}
            maxDate={maxDate}
            disabledDate={disabledDate}
          />
          {showTime && (
            <View className='pd-dateInput__modal__title'>
              <View className='pd-dateInput__modal__title__time'>选择时间：</View>
              <View className='pd-dateInput__modal__picker'>
                <TimePicker
                  timeRange='time'
                  value={dayjs(state.selectedValue[0]).format('HH:mm:ss')}
                  onChange={v => {
                    if (state.selectedValue[0]) {
                      state.selectedValue[0] = dayjs(state.selectedValue[0]).format('YYYY-MM-DD') + ' ' + v;
                    }
                  }}
                />
              </View>
              {mode === 'range' && (
                <View className='pd-dateInput__modal__picker'>
                  <View className='pd-dateInput__modal__title__time'></View>
                  <TimePicker
                    timeRange='time'
                    value={dayjs(state.selectedValue[1]).format('HH:mm:ss')}
                    onChange={v => {
                      if (state.selectedValue[1]) {
                        state.selectedValue[1] = dayjs(state.selectedValue[1]).format('YYYY-MM-DD') + ' ' + v;
                      }
                    }}
                  />
                </View>
              )}
            </View>
          )}
          <Button type='primary' style={{ width: pxTransform(300), alignSelf: 'center', marginTop: pxTransform(30) }} onClick={submit}>
            确定
          </Button>
        </View>
      </PullView>
    </>
  );
};
export default DateInput;
